package kr.couponplay.android.domain.query;

import java.util.ArrayList;
import java.util.List;

import kr.couponplay.android.ApiUrl;
import kr.couponplay.android.support.HttpUtils;

import org.json.JSONArray;
import org.json.JSONObject;

public class QueryDao {
	public RecentQueryList selectRecentQueries(String sid) {
		try {
			List<RecentQuery> queries = new ArrayList<RecentQuery>();
			
        	String result = HttpUtils.execute(ApiUrl.queryBoxUrl + "?sid=" + sid);
        	if (result == null || result.length() == 0) {
        		return new RecentQueryList(0, new ArrayList<RecentQuery>());
        	}

	        JSONArray queryArray = new JSONObject(result).getJSONObject("queryBox").getJSONArray("recentQueries");
			for (int i = 0; i < queryArray.length(); i++) {
				JSONObject object = queryArray.getJSONObject(i);
				
				RecentQuery recentQuery = new RecentQuery();
				recentQuery.setSid(object.getString("sid"));
				recentQuery.setQuery(object.getString("query"));
				recentQuery.setInsertDate(object.getString("insertDate"));
				queries.add(recentQuery);
			}
	        return new RecentQueryList(queries.size(), queries);
		} catch (Exception e) {
			throw new IllegalArgumentException(e);
		}
	}
	
	public int deleteMyRecentQuery(String sid, String query) {
		try {
			if (sid == null || sid.length() == 0) {
				return 0;
			}
			
			if (query == null || query.length() == 0) {
				return 0;
			}
			
			String result = HttpUtils.execute(ApiUrl.deleteQueryUrl + "?sid=" + sid + "&query="+query);
			int count = new JSONObject(result).getInt("count");
			return count;
		} catch (Exception e) {
			throw new IllegalArgumentException();
		}
	}
}
